package com.gxa.service.impl;

import com.gxa.common.Constants;
import com.gxa.common.PageRecv;
import com.gxa.common.PageResult;
import com.gxa.common.R;
import com.gxa.common.exception.CustomerException;
import com.gxa.mapper.*;
import com.gxa.pojo.*;
import com.gxa.service.CustomerPoolService;
import com.gxa.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @program: erp
 * @description: 客户公海模块
 * @author: LC
 * @create: 2021-12-07 19:44
 */

@Service
public class CustomerPoolServiceImpl implements CustomerPoolService {


    @Autowired(required = true)
    CustomerService customerService;

    @Autowired(required = false)
    CustomerMapper customerMapper;

    @Autowired(required = false)
    CustomerEmployeeMapper customerEmployeeMapper;

    @Autowired(required = false)
    CustomerRecordsMapper customerRecordsMapper;

    @Autowired(required = false)
    CustomerPoolMapper customerPoolMapper;

    @Autowired(required = false)
    ContactMapper contactMapper;

    @Override
    public R addCustomer(Customer customer) {
        R r=new R();
        //添加客户
        customer.setStatus(Constants.CUSTOMER_POOL_STATUS);//客户公海状态
        int insertResult = customerMapper.insertCustomer(customer);//传入对象customer
        if(insertResult<=0) throw new CustomerException("插入客户失败");//操作失败则报出异常，触发回滚

        //添加默认联系人，姓名是客户本身
        Contact contact=customer.getContact().get(0);
        contact.setCustomer_id(customer.getCustomer_id());
        contact.setContact_name(customer.getCustomer_name());
        contactMapper.addContact(contact);


        //转入公海
        Customer_Pool customer_pool=new Customer_Pool();
        customer_pool.setApplication_status(Constants.DEFAULT_APPLICATION_STATUS);//设置为默认状态
        customer_pool.setApplication_date(new Date());
        customer_pool.setCustomer(customer);
        Employee employeeCustomerPool=new Employee();
        employeeCustomerPool.setEmployee_id(0);
        customer_pool.setEmployee(employeeCustomerPool);//转入公海后默认无申请业务员,故id为0
        int toPool =customerPoolMapper.insertCustomerPool(customer_pool);//将公海记录存到数据库
        if(toPool<=0) throw new CustomerException(customer.getCustomer_id()+"转入公海失败");

        //添加到客户记录表,当前操作业务员
        Employee employee=new Employee();
        employee.setEmployee_id(7);


        Customer_Records customer_records=new Customer_Records();
        customer_records.setCustomer_id(customer.getCustomer_id());
        customer_records.setUpdate_emp_id(employee.getEmployee_id());
        customer_records.setImport_emp_id(employee.getEmployee_id());
        customer_records.setImport_date(new Date());
        customer_records.setUpdate_date(new Date());
        int customerRecordsResult=customerRecordsMapper.insertRecords(customer_records);
        if(customerRecordsResult<=0) throw new CustomerException("客户日志记录失败");//操作失败则报出异常，触发回滚

        //若成功则返回成功结果
        r.setCode(200);
        r.setMsg(Constants.SUCCESS);
        return r;
    }

    @Override
    public R modifyCustomer(Customer customer) {
        return customerService.modifyCustomer(customer);
    }


    @Override
    public R moveToTrash(List<Integer> customerIds, String remark, List<Integer> delInfo) {
        //移出客户公海
        int delResult=customerPoolMapper.delCustomerPoolByCustomerId(customerIds);
        if(delResult<00) throw new CustomerException("删除公海数据失败");
        //移到回收站
        return customerService.moveToTrash(customerIds,remark,delInfo);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public R moveToOtherEmp(List<Integer> customerIds, Integer employeeId) {
        //转移客户
        R r=customerService.moveToOtherEmp(customerIds,employeeId);
        //将客户公海数据删除
        int delResult=customerPoolMapper.delCustomerPoolByCustomerId(customerIds);
        if(delResult<=0) throw new CustomerException("删除公海数据失败");
        //修改客户状态为普通状态
        int updateResult = customerMapper.updateCustomerListStatus(customerIds, Constants.CUSTOMER_NORMAL_STATUS);
        if(updateResult<=0) throw new CustomerException("修改客户状态为普通状态失败");
        return r;
    }

    /**
     *
     * 返回客户公海实体
     * @param pageRecv
     * @return
     */
    @Override
    public R getCustomerPoolPage(PageRecv<Customer_Pool> pageRecv) {
        R r=new R();
        //获取默认状态或拒绝状态的公海数据
        List<Customer_Pool> customer_pools=customerPoolMapper.selectByDefaultAndFail(pageRecv);
        for (Customer_Pool customer_pool : customer_pools) {
            System.out.println(customer_pool);
            Customer customer=customer_pool.getCustomer();
//            Employee employee=customer_pool.getEmployee();

            //装载客户记录
            //指定客户id的记录
            Customer_Records selectRecords=new Customer_Records();
            selectRecords.setCustomer_id(customer.getCustomer_id());
            //查询出指定客户的操作记录
            Customer_Records customer_records=customerRecordsMapper.selectRecords(selectRecords);
            if(customer_records==null){
                customer_records=new Customer_Records();
            }
            //将查出的操作记录装载入客户
            customer.setCustomer_records(customer_records);

            //装载省市
            Province province=new Province();
            province.setProvince_d(0);
            province.setProvince_name("四川省");
            City city=new City();
            city.setCity_id(0);
            city.setCity_name("成都市");
            city.setProvince(province);
            customer.setCity(city);

            //装载联系人
            List<Contact> contacts = contactMapper.queryContact(customer.getCustomer_id());
            if(contacts.isEmpty()){
                contacts.add(new Contact());
            }
            customer.setContact(contacts);
        }
//            //装载联系人
//            Contact contact=new Contact();
//            contact.setContact_sex(0);
//            contact.setContact_birthday(new Date());
//            contact.setContact_email("1232132141@qq.com");
//            contact.setContact_id(0);
//            contact.setContact_remark("备注");
//            contact.setContact_name("联系人李某");
//            contact.setContact_phone("15122222222");
//            contact.setContact_qq("1178721111");
//            contact.setContact_wechat("SFEWFWE");
//            contact.setPostion("老板");
//            contact.setCustomer_id(0);
//            List<Contact> contacts=new ArrayList();
//            contacts.add(contact);
//            customer.setContact(contacts);
        r.setCode(200);
        r.setMsg(Constants.SUCCESS);
        PageResult pageResult=new PageResult();
        //统计默认状态和拒绝的总条数
        int count=customerPoolMapper.selectCountByDefaultAndFail();
        pageResult.setTotalSize(count);
        pageResult.setList(customer_pools);
        r.setData(pageResult);
        return r;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R applyCustomer(List<Integer> customerPoolIds) {
        R r=new R();
        for (Integer customerPoolId : customerPoolIds) {
            Customer_Pool customer_pool=new Customer_Pool();
            customer_pool.setCp_id(customerPoolId);
            //模拟当前登录业务员
            Employee employee=new Employee();
            employee.setEmployee_id(7);

            //判断是否已经有人申请，若有人申请则不能再申请该客户
            Customer_Pool cp = customerPoolMapper.selectEmployeeByCpId(customer_pool.getCp_id());
            if(cp.getEmployee().getEmployee_id()!=0){//没人申请的客户才可以申请
                throw new  CustomerException("此客户被重复申请（一个客户同一时间只能被一个业务员申请）");
            }

            //更新为正在申请状态
            customer_pool.setEmployee(employee);
            customer_pool.setApplication_date(new Date());
            customer_pool.setApplication_status(Constants.CURERENT_APPLYING_STATUS);//设置状态为申请状态
            int updateResult = customerPoolMapper.updateCustomerPool(customer_pool);
            if(updateResult<=0) throw new CustomerException("申请操作失败");
        }
        r.setCode(200);
        r.setMsg(Constants.SUCCESS);
        return r;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public R reviewApplication(List<Customer_Pool> customer_Pools) {
        R r=new R();
        for (Customer_Pool customer_pool : customer_Pools) {
            if(customer_pool.getApplication_status()==Constants.APPLICATION_SUCCESS_STATUS){//审核成功，存入客户关系表,删除客户在公海的数据，修改客户状态为正常
                //存入客户关系表
                Customer customer=customer_pool.getCustomer();
                Employee employee=customer_pool.getEmployee();
                Customer_Employee customer_employee=new Customer_Employee();
                customer_employee.setCustomer(customer);
                customer_employee.setEmployee(employee);
                Integer insertResult = customerEmployeeMapper.insertRelationship(customer_employee);
                if(insertResult<=0) throw new CustomerException("客户员工关系建立失败");

                //删除客户公海数据
                int delResult = customerPoolMapper.delCustomerPoolById(customer_pool.getCp_id());
                if(delResult<=0) throw new CustomerException("删除客户公海数据失败");

                //修改客户状态为普通状态
                int updateResult = customerMapper.updateCustomerStatus(customer.getCustomer_id(), Constants.CUSTOMER_NORMAL_STATUS);
                if(updateResult<=0) throw new CustomerException("修改客户状态为普通状态失败");

            }else {//审核失败，客户继续在公海中，将客户公海状态改为失败
                customer_pool.setCp_id(customer_pool.getCp_id());
                customer_pool.setApplication_date(new Date());
                customer_pool.setApplication_status(Constants.APPLICATION_FAIL_STATUS);//设置为申请失败状态
                int updateResult = customerPoolMapper.updateCustomerPool(customer_pool);
                if (updateResult <= 0) throw new CustomerException("审核失败");
            }
        }
        r.setCode(200);
        r.setMsg(Constants.SUCCESS);
        return r;
    }

    //审核数量
    @Override
    public R getCountByApplication() {
        R r=new R();
        //统计正在申请状态
        int count=customerPoolMapper.selectCountByApplying();
        r.setCode(200);
        r.setMsg(Constants.SUCCESS);
        r.setData(count);
        return r;
    }

    @Override
    public R getCustomerPoolByApplication(PageRecv<Customer_Pool> pageRecv) {
        R r=new R();
        //获取正在申请的数据
        List<Customer_Pool> customer_pools=customerPoolMapper.selectByApplying(pageRecv);
        for (Customer_Pool customer_pool : customer_pools) {
            Customer customer=customer_pool.getCustomer();
//            Employee employee=customer_pool.getEmployee();
            //装载客户记录
            //指定客户id的记录
            Customer_Records selectRecords=new Customer_Records();
            selectRecords.setCustomer_id(customer.getCustomer_id());
            //查询出指定客户的操作记录
            Customer_Records customer_records=customerRecordsMapper.selectRecords(selectRecords);
            if(customer_records==null){
                customer_records=new Customer_Records();
            }
            //将查出的操作记录装载入客户
            customer.setCustomer_records(customer_records);

            //装载省市
            Province province=new Province();
            province.setProvince_d(0);
            province.setProvince_name("四川省");
            City city=new City();
            city.setCity_id(0);
            city.setCity_name("重庆市");
            city.setProvince(province);
            customer.setCity(city);
            //装载联系人
            List<Contact> contacts = contactMapper.queryContact(customer.getCustomer_id());
            customer.setContact(contacts);
        }
//            //装载联系人
//            Contact contact=new Contact();
//            contact.setContact_sex(0);
//            contact.setContact_birthday(new Date());
//            contact.setContact_email("1232132141@qq.com");
//            contact.setContact_id(0);
//            contact.setContact_remark("备注");
//            contact.setContact_name("联系人李某");
//            contact.setContact_phone("15122222222");
//            contact.setContact_qq("1178721111");
//            contact.setContact_wechat("SFEWFWE");
//            contact.setPostion("老板");
//            contact.setCustomer_id(0);
//            List<Contact> contacts=new ArrayList();
//            contacts.add(contact);
//            customer.setContact(contacts);
        r.setCode(200);
        r.setMsg(Constants.SUCCESS);
        PageResult pageResult=new PageResult();
        //统计正在申请状态
        int count=customerPoolMapper.selectCountByApplying();
        pageResult.setTotalSize(count);
        pageResult.setList(customer_pools);
        r.setData(pageResult);
        return r;
    }

}